package com.duoketech.interceptor;

import com.duoketech.model.member.Member;
import com.duoketech.utils.DbUtil;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;

public class WxMemberInterceptor  implements Interceptor {
    @Override
    public void intercept(Invocation invocation) {
        Controller c = invocation.getController();
        String returnUrl = getCurrentUrl(c);
        int memberId = c.getCookieToInt("memberId",0);
        Member member = DbUtil.getMember(memberId);
        if(member!=null){
            invocation.invoke();
        }else{
            if(StringUtils.isNotEmpty(returnUrl)){
                returnUrl = URLEncoder.encode(returnUrl);
                c.redirect("/weixin/login?returnUrl="+returnUrl);
            }else{
                c.redirect("/weixin/login");
            }
        }
    }

    public String getCurrentUrl(Controller c){
        HttpServletRequest request = c.getRequest();
        String url = request.getRequestURI();
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        String queryString = request.getQueryString();
        url = (queryString==null)?scheme+"://"+serverName+url:scheme+"://"+serverName+url+"?"+queryString;
        System.out.println(url);
        return url;
    }
}
